package com.nexgo.payment.trans.download;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.common.ByteUtils;
import com.nexgo.common.TlvUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.emv.EmvHandler;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsOnlinePresenter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by xiaox on 2017/8/11.
 */
public class CapkParamPresenter extends AbsOnlinePresenter implements DownloadTransContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(CapkParamPresenter.class.getSimpleName());

    private DownloadTransContract.View mView;
    private List<String> mCapkList;
    private int mTotal = 0;

    protected CapkParamPresenter(@NonNull DownloadTransContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
        mCapkList = new ArrayList<>();
    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
//        transData.setTransType(TransType.CAPK_NOTIFY);
//        wzp add
        transData.setTransType(TransType.CAPK_DOWN);
//        交行第一次下载都位0
        transData.setTemporary("0000");
        return transData;
    }

    @Override
    protected void onFirstAction() {
//        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_notify)));
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_down)));
    }

    @Override
    protected void onTransSuccess(RecvData recvData) {
        if (TransType.CAPK_NOTIFY.equals(mTransData.getTransType())) {
            //查询包
            if (TextUtils.isEmpty(recvData.getField62())) {
                postMainThread(() -> mView.showTransFailed());
                return;
            }
            byte[] value = ByteUtils.hexString2ByteArray(recvData.getField62());
            byte mode = value[0];
            if (mode == '0') {
                mTransData.setTransType(TransType.CAPK_END);
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_end)));
            } else if (mode == '1' || mode == '2' || mode == '3') {
                //1表示只有一条
                //2表示要继续发起通知查询
                //3表示最后一条
                //缓存起capk索引数据，用于发送capk下载包用
                String rid = ByteUtils.byteArray2HexString(Arrays.copyOfRange(value, 1, value.length));
                List<String> ridList = TlvUtils.decodingTLV(rid, "9f06");
                if (ridList == null || ridList.size() == 0) {
                    postMainThread(() -> mView.showTransFailed());
                    return;
                }
                mTransData.setCounter(mTransData.getCounter() + ridList.size());
                mTransData.setTemporary(mTransData.getTemporary() + rid);
                if (mode != '2') {
                    //改交易类型，发起capk下载包
                    mTotal = mTransData.getCounter();
                    mTransData.setTransType(TransType.CAPK_DOWN);
                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_down)));
                } else {
                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_notify)));
                }
            } else {
                postMainThread(() -> mView.showTransFailed());
            }
        } else if (TransType.CAPK_DOWN.equals(mTransData.getTransType())) {
            //下载包

//            wzp add
            byte[] value = ByteUtils.hexString2ByteArray(recvData.getField60());
            if (value == null || value.length <= 1) {
                postMainThread(() -> mView.showTransFailed());
                return;
            }
   /*         byte mode = value[0];
            if (mode == '1') {
                mCapkList.add(ByteUtils.byteArray2HexString(Arrays.copyOfRange(value, 1, value.length)));
            }*/
            mCapkList.add(ByteUtils.byteArray2HexString(value));
            //计数器自减
//            mTransData.setCounter(mTransData.getCounter() - 1);
//            28域是1表示下载完
            int over = Integer.parseInt(recvData.getfield28());
            mLog.debug("getfield28 over {}",over);
            if (over == 0) {
                //计数器为0，开始下灌capk列表
                EmvHandler sdkEmvHandler = ApiDeviceEngine.getInstance().getEmvHandler(SysConstant.EMV_OPERAT_PATH);
                sdkEmvHandler.delAllCapk();
                for (String capk : mCapkList) {
                    mLog.debug("{}", capk);
                }
                int ret = sdkEmvHandler.setCAPKList(mCapkList);
                if (ret == SdkResult.Success) {
                    //结束包
                    postMainThread(() -> mView.showTransSuccess());
//                    mTransData.setTransType(TransType.CAPK_END);
//                    postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_end)));
                } else {
                    postMainThread(() -> mView.showTransFailed());
                }
            } else {
                //继续发起capk下载包
                //wzp add 获取CAPK 下载偏移
                mLog.debug("recvData getTrack2 {}",recvData.getTrack2());
                mTransData.setTemporary(recvData.getTrack2());
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_down)));
//                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.capk_down, String.valueOf(mTotal - mTransData.getCounter() + 1), String.valueOf(mTotal))));
            }
        } else {
            //结束包
            postMainThread(() -> mView.showTransSuccess());
        }
    }
}
